let db = require("../db/index")



let axios = require("axios")

const plugins = require("../utils/index")

// 导入公共函数

let publicFc = require("../utils/index")

// 导入jwt和express-jwt
const jwt = require("jsonwebtoken")
const expressJWT = require("express-jwt")





// 发送用户信息
emitUserPid = (req,res)=>{
    
   let code = req.query.code
//    console.log(code)
    axios.get("https://api.weixin.qq.com/sns/jscode2session",{params:{
        appid:"wxb4e0b0a226269dc2",
        secret:"65fa5ebfa853f2e1eb3299ee5f463677",
        js_code:code,
        grant_type:"authorization_code"
    }}).then(result=>{
         // 生成token
        //  openId
        let openId = result.data.openid
        // 用户的名字
        result.data.userName = req.query.nickName
        //用户的性别
        result.data.gender = req.query.gender
        // 用户的头像
        result.data.userImg = req.query.avatarUrl
        

        let sql ="select * from userlist where openId = ?"

        return new Promise((resolve,reject)=>{
            db.query(sql,openId,(err,succ)=>{

                if(succ.length>0) return resolve(succ)
                if(succ.length==0) return reject(result.data)
            })
        })


       
    }).then(a=>{
        // console.log(a)
        const token = jwt.sign({userName:a[0].userName,openId:a[0].openId},publicFc.secret(),{expiresIn:"120s"})
        
        res.send({
            status:200,
            data:{
                userName:a[0].userName,
                openid:a[0].openId,
                gender:a[0].gender,
                userImg:a[0].userImg,
                token
            },
         
            mess:"已有的数据"
        })
        
        return new Promise(()=>{})
        
     
    },b=>{
            let sql ="insert into userlist set ?"

        return new Promise((resolve,reject)=>{
            db.query(sql,{openId:b.openid,userName:b.userName,gender:b.gender,userImg:b.userImg},(err,success)=>{
                if(err) return reject(err)
                if(success.affectedRows == 1) return resolve(b)
            })
        })  
    })
    .then(r=>{
        const token = jwt.sign({userName:r.userName,openId:r.openid},publicFc.secret(),{expiresIn:"120s"})
          res.send({
            status:200,
            data:{
                ...r,
                token,
            },
            mess:"插入数据成功"
        })
    },e=>{
        res.send({
            status:401,
            mess:e
        })
    }).catch(err=>{
        console.log("飞洒咖啡就二十")
        res.send({
            status:401,
            mess:err
        })      
    })
  
}

// 获取路由信息
getRouterInfo = (req,res)=>{
    let sql = "select * from router"
    let p = new Promise((resolve,reject)=>{
        db.query(sql,"",(err,result)=>{
            if(err)return reject("获取失败")
            if(result.length>0){
                resolve(result)
            }else{
                resolve([])
            }
        })
    })

    p.then(r=>{
        res.send({
            status:200,
            data:r,
            mess:"获取数据成功"
        })
    },e=>{
        res.send({
            status:400,
            mess:e
        })
    })
}

// 插入等级权限
insertAuthority=(req,res)=>{
    let data = req.query
  
    let sql = "insert into userauth set ?"
    let p = new Promise((resolve,reject)=>{
        db.query(sql,data,(err,result)=>{
            if(err)return reject("插入失败")
            if(result.affectedRows>0){
                return resolve("插入成功")
            }else{
                return reject("插入失败")
            }
        })
    })
    p.then(r=>{
        res.send({
            status:200,
            mess:r
        })
    },e=>{
        res.send({
            status:400,
            mess:e
        })
    })

}

// 用户注册
userRegister=(req,res)=>{
    let data = req.query
    data.adduserDate = plugins.dateConversion(new Date())
    // let sql = "insert into regiter set ?"
    let sql = "select * from register where phone = ?"

    let p1 = new Promise((resolve,reject)=>{
        db.query(sql,data.phone,(err,result)=>{
            if(err)return reject()
            if(result.length>0){
                resolve("用户已有")
            }else{
                reject("注册")
            }
        })
    })
    p1.then(r=>{
        res.send({
            status:201,
            mess:"账户已有"
        })
    },e=>{
        let sql1 = "insert into register set ?"
        let p = new Promise((resolve,reject)=>{
            db.query(sql1,data,(err,result)=>{
                if(err) return reject(err)

                if(result.affectedRows>0){
                    return resolve("注册成功")
                }else{
                    return reject("注册失败")
                }
            })
        })
        p.then(r=>{
            res.send({
                status:200,
                mess:r
            })
        },e=>{
            res.send({
                status:400,
                mess:e
            })
        })


    })


    // let p = new Promise((resolve,reject)=>{
    //     db.query(sql,data,(err,result)=>{
    //         if(err) return reject(err)

    //         if(result.affectedRows>0){
    //             return resolve("注册成功")
    //         }else{
    //             return reject("注册失败")
    //         }
    //     })
    // })
    // p.then(r=>{
    //     res.send({
    //         status:200,
    //         mess:r
    //     })
    // },e=>{
    //     res.send({
    //         status:400,
    //         mess:e
    //     })
    // })

}

// 用户删除
deleteUser = (req,res)=>{
    let id = req.query.id
    let sql ="delete from register where id =?"
    
    let p = new Promise((resolve,reject)=>{
        db.query(sql,id,(err,result)=>{
            if(err) return reject("删除失败")
            if(result.affectedRows>0){
                return resolve("删除成功")
            }else{
                return reject("删除失败")
            }
        })
    })
    p.then(r=>{
        res.send({
            status:200,
            mess:r
        })
    },e=>{
        res.send({
            status:400,
            mess:e
        })
    })
}

// 获取用户所有数据
getUserData = (req,res)=>{
    let sql = "select * from register"
    let p = new Promise((resolve,reject)=>{
        db.query(sql,"",(err,result)=>{
            if(err) return reject
            if(result.length>0){
                resolve(result)
            }else{
                resolve([])
            }
        })
    })
    p.then(r=>{
        r.forEach(item=>{
            item.adduserDate = plugins.dateConversion(item.adduserDate)
        })
        console.log(r)
        res.send({
            status:200,
            data:r,
            mess:"获取数据成功"
        })
    },e=>{
        res.send({
            status:400,
            data:r,
            mess:"获取数据失败"
        })
    })
}

// 编辑用户
editUser = (req,res)=>{
    let id= req.query.id
    let data = req.query
    let sql = "update register set ? where id =?"

    let p = new Promise((resolve,reject)=>{
        db.query(sql,[data,id],(err,result)=>{
            if(err) return reject(err)
            if(result.affectedRows>0){
                return resolve("编辑成功")
            }else{
                return reject("编辑失败")
            }
        })
    })
    p.then(r=>{
        res.send({
            status:200,
            mess:r
        })
    },e=>{
        res.send({
            status:400,
            mess:e
        })
    })
}

// 用户登录

login = (req,res)=>{

    // console.log(req.query)
    let data = req.query
    let sql1 = "select * from router" //获取路由数据
    let sql2 = "select * from userauth" //获取权限
    let sql3 = "select * from register where phone=? and password=?" //获取用户登录的数据

    let p1 = new Promise((resolve,reject)=>{
        db.query(sql1,"",(err,result)=>{
            if(err) return reject(err)
            if(result.length>0){
                return resolve(result)
            }else{
                return resolve([])
            }
        })
    })

    let p2 = new Promise((resolve,reject)=>{
        db.query(sql2,"",(err,result)=>{
            if(err) return reject(err)
            if(result.length>0){
                return resolve(result)
            }else{
                return resolve([])
            }
        })
    })

    let p3 = new Promise((resolve,reject)=>{
        db.query(sql3,[data.phone,data.password],(err,result)=>{
            if(err) return reject(err)
            if(result.length>0){
                return resolve(result)
            }else{
                return reject([])
            }
        })
    })
    
    let p = Promise.all([p1,p2,p3])

    p.then(r=>{
       
        // console.log(r[2][0].authclass)
        let userinfo = r[2][0]
        let token = jwt.sign({id:userinfo.id,phone:userinfo.phone},publicFc.secret(),{expiresIn:"1h"}) //用户的信息
        let authclass =r[2][0].authclass //路由权限等级
        let routesList = JSON.parse(r[1].filter(item=>item.authclass ==authclass)[0].auth) //全部的路由权限
        let routes = [] //把路由返回
        r[0].map(item=>{
            routesList.forEach(info=>{
                if(item.id==info){
                    routes.push(item)
                }
            })
        })

        res.send({
            status:200,
            data:{
                routes,
                token:token,
                userinfo:{
                    ...userinfo,
                    password:null
                }
            },
            mess:"登录成功"
        })
    },e=>{
        res.send({
            status:400,
            err:e,
            mess:"密码错误"
        })
    })

}




module.exports = {
    emitUserPid,
    getRouterInfo,
    insertAuthority,
    userRegister,
    getUserData,
    login,
    deleteUser,
    editUser
}
